﻿/* Copyright ReflectionReturning.cs Killian Bourrié
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

namespace NTracker.Toolkit
{
    using System;
    using System.Dynamic;
    using System.Reflection;

    public sealed class ReflectionReturning : DynamicObject
    {
        private ReflectionCaller caller;

        public ReflectionReturning(ReflectionCaller caller)
        {
            this.caller = caller;
        }

        public override bool TryConvert(ConvertBinder binder, out object result)
        {
            // if object contains at least one constructor without parameters
            if (binder.Type.GetConstructor(Type.EmptyTypes) != null)
            {
                result = Activator.CreateInstance(binder.Type);
            }
            else
            {
                // else intances them one by one
                if (this.caller.Resolver.ReturnCustomValues != null)
                {
                    result = this.caller.Resolver.ReturnCustomValues(binder.Type);
                }
                else
                {
                    result = default(object);
                }
            }

            return true;
        }
    }
}
